import json
from typing import Any
from django.http import JsonResponse
from django.core.handlers.wsgi import WSGIRequest
from django.db import transaction
from django.core.cache import cache


from rest_framework.parsers import JSONParser
from rest_framework import status


from .models import UserRechargeOrder, UserRechargeType
from .serializers import UserSerializer, get_detail_UserPackage
from . import wxapi

import requests

from jqexception.jqexecption import (
    jq_try,
    UnknowErr,
    RaffleBusyErr,
    RightErr,
    NullErr,
    ReqMethodErr,
    ValueErr,
)


import logging

logger = logging.getLogger("log")


# 支付接口
# 统一下单	http://api.weixin.qq.com/_/pay/unifiedorder
# doc https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/development/pay/order/unified.html
def unifiedorder(request, total_fee, call_back_url, order_title, *args, **kwargs):
    if total_fee < 1:
        raise ValueErr

    openid = request.META.get("HTTP_X_WX_OPENID", None)
    if not openid:
        raise NullErr

    userRechargeOrder = UserRechargeOrder(
        total_fee=total_fee, openid=openid, recharge_type=UserRechargeType.weixin
    )
    userRechargeOrder.save()

    spbill_create_ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
    if not spbill_create_ip:
        raise NullErr

    env_id = request.META.get("HTTP_X_WX_ENV", None)
    if not env_id:
        raise NullErr

    mch_id = cache.get("MCH_ID", None)
    if not mch_id:
        raise NullErr

    service = request.META.get("HTTP_X_WX_SERVICE", None)

    params = {
        "body": order_title,
        "openid": openid,
        "out_trade_no": userRechargeOrder.out_trade_no,
        "spbill_create_ip": spbill_create_ip,
        "env_id": env_id,
        "sub_mch_id": mch_id,
        "total_fee": total_fee,
        "callback_type": 2,
        "container": {"service": service, "path": call_back_url},
    }

    res = requests.post(
        url=f"{wxapi.unifiedorder}",
        json=params,
        headers={
            "Content-Type": "application/json",
        },
    )

    d = json.loads(res.content)

    logger.debug(f"response content: {res.content}")
    logger.debug(f"req params: {params}")
    logger.debug(f"req params: {d}")

    if d["errcode"] != 0:
        raise ValueErr

    return d, userRechargeOrder.out_trade_no


# 查询订单	http://api.weixin.qq.com/_/pay/queryorder
def queryorder(request, *args, **kwargs):
    pass


# 关闭订单	http://api.weixin.qq.com/_/pay/closeorder
def closeorder(request, *args, **kwargs):
    pass


# 下载对账单	http://api.weixin.qq.com/_/pay/downloadbill
def downloadbill(request, *args, **kwargs):
    pass


# 申请退款	http://api.weixin.qq.com/_/pay/refund
def refund(request, *args, **kwargs):
    pass


# 查询退款	http://api.weixin.qq.com/_/pay/queryrefund
def queryrefund(request, *args, **kwargs):
    pass
